'use strict';
const Service = require('egg').Service;
const path = require('path');
const mkdirp = require('mkdirp');
const fs = require('fs');
const TOP_LEVEL_RETAIN = 'TOP_LEVEL_RETAIN'; // 自定义顶级分类CODE
class ClassifyService extends Service {
  /**
   * 新增分类
   */
  async addClassify() {
    const { ctx } = this;
    try {
      ctx.request.body.createdTime = ctx.helper.dateReset(
        new Date(),
        'yyyy-MM-dd hh:mm:ss'
      );
      // 判断是否存在顶级分类
      const topLevel = await ctx.model.Classify.findOne({
        classifyName: TOP_LEVEL_RETAIN,
      });
      const { parent, classifyName } = ctx.request.body;
      let isRepeat = await ctx.model.Classify.findOne({
        classifyName,
        parent: parent ? parent : topLevel ? topLevel : null,
      }); // 条件查询
      if (isRepeat) {
        ctx.helper.fail({
          ctx,
          code: 422,
          res: {},
          detailMessage: '当前层级下已存在相同名称的目录',
        });
        return;
      }
      // 新增一级分类
      if (!parent) {
        let topLevel = null;
        // 判断是否存在顶级分类
        topLevel = await ctx.model.Classify.findOne({
          classifyName: TOP_LEVEL_RETAIN,
        });
        if (!topLevel) {
          // 创建默认顶级分类
          topLevel = await ctx.model.Classify.create({
            classifyName: TOP_LEVEL_RETAIN,
            classifyDescribe: '顶级分类',
            createdTime: ctx.helper.dateReset(
              new Date(),
              'yyyy-MM-dd hh:mm:ss'
            ),
            lastUpdateTime: ctx.helper.dateReset(
              new Date(),
              'yyyy-MM-dd hh:mm:ss'
            ),
          });
        }
        ctx.request.body.lastUpdateTime = ctx.helper.dateReset(
          new Date(),
          'yyyy-MM-dd hh:mm:ss'
        );
        const newChild = Object.assign(ctx.request.body, {
          parent: topLevel,
        });
        // 在顶级分类下创建一级分类
        const res = await ctx.model.Classify.create(newChild);
        const uploadDirPath = `app/public/${classifyName}`;
        const dir = path.join(uploadDirPath);
        await mkdirp(dir); // 创建目录
        ctx.helper.success({
          ctx,
          code: 200,
          res,
        });
        return;
      }
      // 新增子级分类
      let parentClass = await ctx.model.Classify.findById(parent); // 条件查询
      if (!parentClass) {
        ctx.helper.fail({
          ctx,
          code: 422,
          res: {},
          detailMessage: '未找到该父级分类',
        });
        return;
      }
      const newChild = Object.assign(ctx.request.body, {
        parent: parentClass,
      });
      const res = await ctx.model.Classify.create(newChild);
      const uploadDirPath = `app/public/${parentClass.classifyName}/${classifyName}`;
      const dir = path.join(uploadDirPath);
      await mkdirp(dir); // 创建目录
      ctx.helper.success({
        ctx,
        code: 200,
        res,
      });
    } catch (err) {
      ctx.logger.error(err);
      ctx.helper.fail({ ctx, code: 500, res: '后端接口异常！' });
    }
  }
  // 查询目录树
  async findClassify() {
    const { ctx } = this;
    try {
      const { _id } = ctx.request.query;
      let parentNode = null;
      if (_id) {
        parentNode = await ctx.model.Classify.findOne({
          _id,
        });
      } else {
        parentNode = await ctx.model.Classify.findOne({
          classifyName: TOP_LEVEL_RETAIN,
        });
      }
      let treeNode = [];
      if (parentNode) {
        const filters = {};
        treeNode = await parentNode.getChildrenTree({
          filters, //  过滤
          // fields: '_id name', // 字段选择
          options: { sort: {} }, //  排序
          // populate: 'repos',
          // minLevel: 2,
          // maxLevel: 4,
        });
      }
      ctx.helper.success({
        ctx,
        code: 200,
        res: treeNode,
      });
    } catch (err) {
      ctx.logger.error(err);
      ctx.helper.fail({ ctx, code: 500, res: '后端接口异常！' });
    }
  }
  // 修改目录
  async updateClassify() {
    const { ctx } = this;
    try {
      let params = ctx.request.body;
      let oldData = await ctx.model.Classify.findById(params._id);
      const parent = await ctx.model.Classify.findById(oldData.parent);
      const isHaveIdent = await ctx.model.Classify.findOne({
        parent: parent._id,
        classifyName: params.classifyName,
      });
      if (isHaveIdent) {
        ctx.helper.fail({
          ctx,
          code: 500,
          res: {},
          detailMessage: `同级分类下已存在${params.classifyName}`,
        });
        return;
      }
      const oldPath = path.join(
        parent.classifyName !== TOP_LEVEL_RETAIN
          ? `app/public/${parent.classifyName}/${oldData.classifyName}/`
          : `app/public/${oldData.classifyName}/`
      );
      //   try {
      //     const files = await fs.readdirSync(oldPath);
      //     if (files.length) {
      //       ctx.helper.fail({
      //         ctx,
      //         code: 500,
      //         res: '当前文件夹下面还有其它内容，不可修改',
      //         detailMessage: '当前文件夹下面还有其它内容，不可修改',
      //       });
      //       return;
      //     }
      //   } catch (error) {
      //     ctx.logger.error(error);
      //     ctx.helper.fail({ ctx, code: 500, res: error });
      //   }

      const newPath = path.join(
        parent.classifyName !== TOP_LEVEL_RETAIN
          ? `app/public/${parent.classifyName}/${params.classifyName}/`
          : `app/public/${params.classifyName}/`
      );
      await fs.renameSync(oldPath, newPath);
      // 修改的数据
      let setData = {
        classifyName: params.classifyName,
        classifyDescribe: params.classifyDescribe,
        lastUpdateTime: ctx.helper.dateReset(new Date(), 'yyyy-MM-dd hh:mm:ss'),
      };
      let categoryData = await ctx.model.Classify.findOneAndUpdate(
        {
          _id: params._id,
        },
        {
          $set: setData,
        },
        { new: true }
      );
      ctx.helper.success({
        ctx,
        code: 200,
        res: categoryData,
      });
    } catch (err) {
      ctx.logger.error(err);
      ctx.helper.fail({ ctx, code: 500, res: '后端接口异常！' });
    }
  }
  // 删除目录
  async deleteClassify(classify_id) {
    const { ctx } = this;
    try {
      const classifyData = await ctx.model.Classify.findById(classify_id);
      const parentData = await ctx.model.Classify.findById(classifyData.parent);
      const childData = await classifyData.getChildrenTree({});
      if (childData && childData.length) {
        ctx.helper.fail({
          ctx,
          code: 422,
          res: '当前目录存在子目录，无法删除',
          detailMessage: '当前目录存在子目录，无法删除',
        });
        return;
      }
      const pathUrl =
        parentData.classifyName !== TOP_LEVEL_RETAIN
          ? `app/public/${parentData.classifyName}/${classifyData.classifyName}/`
          : `app/public/${classifyData.classifyName}/`;
      try {
        await fs.rmdirSync(pathUrl);
      } catch (error) {}
      await ctx.model.Classify.deleteOne({ _id: classify_id });
      ctx.helper.success({
        ctx,
        code: 200,
        res: {},
      });
    } catch (err) {
      ctx.logger.error(err);
      ctx.helper.fail({ ctx, code: 500, res: '后端接口异常！' });
    }
  }
}
module.exports = ClassifyService;
